<!-- 登录 -->
<template>
  <el-container class="login">
    <el-card class="dialog">
      <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules">
        <el-form-item label="账户" prop="username">
          <el-input v-model="ruleForm.username" placeholder="请输入账户" />
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input
            v-model="ruleForm.password"
            placeholder="请输入密码"
            type="password"
          />
        </el-form-item>

        <el-form-item label="确认" prop="checkPass">
          <el-input
            v-model="ruleForm.checkPass"
            placeholder="请确认密码"
            type="password"
          />
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            style="width: 100%"
            @click="submitForm(ruleFormRef)"
          >
            注册
          </el-button>
          Or
          <el-button
            type="text"
            style="color: black"
            @click="$router.replace('/login')"
          >
            去登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-container>
</template>

<script setup>
import { ElMessage } from "element-plus";
import { reactive, ref } from "vue";
import { apiRegister } from "@/api/register";

const ruleFormRef = ref();

const ruleForm = reactive({});

const rules = reactive({
  username: [
    {
      required: true,
      message: "账户不能为空",
      target: "blur",
    },
  ],
  password: [
    {
      required: true,
      message: "密码不能为空",
      target: "blur",
    },
  ],
  checkPass: [
    {
      required: true,
      message: "两次密码输入不一致",
      target: "blur",
    },
  ],
});

// 校验
const submitForm = async (formEl) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (ruleForm.password.trim() !== ruleForm.checkPass.trim()) {
      ElMessage.error("两次密码输入不一致");
    } else {
      // 校验成功
      if (valid) {
        apiRegister(ruleForm).then((res) => {
          console.log(res);
        });
      }
      // 校验失败
      else {
        console.log("error submit!", fields);
      }
    }
  });
};
</script>

<style scoped lang="scss">
.login {
  background: url("https://img1.baidu.com/it/u=2866452612,2730964424&fm=253&fmt=auto&app=138&f=JPEG?w=667&h=500");
  background-repeat: no-repeat;
  background-size: cover;
}
.dialog {
  width: 500px;
  position: absolute;
  top: 30%;
  right: 10%;
}
</style>
